//  数字取万
const parseNum = num => {
  if (!num) {
    return 0
  }
  num = +num;
  if (num < 10000) return num;
  const obj = new Number(num / 10000);
  let rt = obj.toFixed(1);
  const arr = rt.split('.');
  if (+arr[1] === 0) {
    rt = arr[0]
  }
  return `${rt}万`;
};

//  格式化时间
const parseTime = (time, cFormat) => {
  if (arguments.length === 0) {
    return null;
  }
  if ((time + '').length === 10) {
    time = +time * 1000
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}';
  let date;
  if (typeof time === 'object') {
    date = time;
  } else {
    date = new Date(parseInt(time));
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  };
  return format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key];
    if (key === 'a') return ['一', '二', '三', '四', '五', '六', '日'][value - 1];
    if (result.length > 0 && value < 10) {
      value = '0' + value;
    }
    return value || 0;
  });
}

// 格式化rich-text
const formatRichText = html => {
  let newContent = html.replace(/\<img/gi, '<img style="width:100%;height:auto;display:block;"').replace(
    /\<div style=\"/gi, '<div style="width:100%;word-break:break-all;word-wrap:normal;').replace(/\s{2,}/g, "")
  return newContent
}

// 使用时间
const timeDifference = (timer) => {
  const mouth = parseInt((timer / 1000 / 60 / 60 / 24 / 30)); //月
  const day = parseInt((timer / 1000 / 60 / 60 / 24)); //日
  let hours = parseInt((timer / 1000 / 60 / 60 % 24)); //时
  let minutes = parseInt((timer / 1000 / 60 % 60)); //分
  let seconds = parseInt((timer / 1000 % 60)); //秒
  hours = hours < 0 ? '0' + hours : hours;
  minutes = minutes < 0 ? '0' + minutes : minutes;
  seconds = seconds < 0 ? '0' + seconds : seconds;

  let str = '';
  if (mouth > 0) {
    str = mouth + '月' + day + '天' + hours + '时' + minutes + '分' + seconds + '秒';
  } else if (day > 0) {
    str = day + '天' + hours + '时' + minutes + '分' + seconds + '秒';
  } else if (hours > 0) {
    str = hours + '时' + minutes + '分' + seconds + '秒';
  } else if (minutes > 0) {
    str = minutes + '分' + seconds + '秒';
  } else {
    str = seconds + '秒';
  }
  return str
}

/**
 * 字典值替换文本通用方法
 * @param dictOptions  字典数组
 * @param text  字典值
 * @return String
 */
const filterDictText = (dictOptions, text) => {
  if (text != null && Array.isArray(dictOptions)) {
    const result = []
    // 允许多个逗号分隔，允许传数组对象
    let splitText
    if (Array.isArray(text)) {
      splitText = text
    } else {
      splitText = text.toString().trim().split(',')
    }
    for (let txt of splitText) {
      let dictText = txt
      for (let dictItem of dictOptions) {
        if (txt.toString() === dictItem.value.toString()) {
          // 如果追加有class，优先返回class
          dictText = (dictItem.class || dictItem.text || dictItem.title || dictItem.label)
          break
        }
      }
      result.push(dictText)
    }
    return result.join(',')
  }
  return text
}

// 格式化价格（分 → 元）
const formatYuan = (amount) => {
  if (!amount) {
    return '0.00'
  }
  return (amount / 100).toFixed(2)
}

// 格式化日期: yyyy-MM-dd
const formatDate = (date) => {
  const year = date.getFullYear()
  let month = date.getMonth() + 1
  let day = date.getDate()
  if (month < 10) {
    month = `0${month}`
  }
  if (day < 10) {
    day = `0${day}`
  }
  return (`${year}-${month}-${day}`)
}

// 获取今日日期开始和结束日期: [yyyy-MM-dd, yyyy-MM-dd] 筛选条件用，输出数组
const getToday = () => {
  const str = formatDate(new Date());
  return [str, str]
}

// 获取昨日开始和结束日期: [yyyy-MM-dd, yyyy-MM-dd] 筛选条件用，输出数组
const getYesterday = () => {
  const date = new Date()
  const year = date.getFullYear()
  const month = date.getMonth()
  const day = date.getDate()
  const str = formatDate(new Date(year, month, day - 1));
  return [str, str]
}

// 获取本周开始和结束日期: [yyyy-MM-dd, yyyy-MM-dd]
const getThisWeek = () => {
  // 1.创建Date对象
  const date = new Date()
  // 2.获取今日的年月日，及周几
  const year = date.getFullYear()
  const month = date.getMonth()
  const day = date.getDate()
  const week = date.getDay()
  // 3.获取本周开始日期并格式化为yyyy-MM-dd格式
  const thisWeekStartDate = formatDate(new Date(year, month, day - week + 1))
  // 若本周开始日期为上月月底日期也无需担心，如new Date()中的参数为2022,3,-3,则此条语句会输出2022-03-28
  // 4.获取本周结束日期并格式化为yyyy-MM-dd格式
  const thisWeekEndDate = formatDate(new Date(year, month, day - week + 7))
  const thisWeek = []
  thisWeek.push(thisWeekStartDate, thisWeekEndDate)
  // 5.返回结果
  return thisWeek
}

// 获取本月开始和结束日期: [yyyy-MM-dd, yyyy-MM-dd]
const getThisMonth = () => {
  const date = new Date()
  const year = date.getFullYear()
  const month = date.getMonth()
  const thisMonthStartDate = formatDate(new Date(year, month, 1))
  const thisMonthEndDate = formatDate(new Date(year, month + 1, 0))
  // 下个月第0天表示本月最后一天
  const thisMonth = []
  thisMonth.push(thisMonthStartDate, thisMonthEndDate)
  return thisMonth
}

// 获取n天前的开始和结束日期: [yyyy-MM-dd, yyyy-MM-dd] 筛选条件用，输出数组
const getDayAgo = (n) => {
  const date = new Date()
  const year = date.getFullYear()
  const month = date.getMonth()
  const day = date.getDate();
  const today = formatDate(new Date());
  const str = formatDate(new Date(year, month, day - n + 1));
  return [str, today]
}

// 获取n月前的开始和结束日期: [yyyy-MM-dd, yyyy-MM-dd] 筛选条件用，输出数组
const getMonthAgo = (n) => {
  const date = new Date()
  const year = date.getFullYear()
  const month = date.getMonth()
  const today = formatDate(new Date());
  const str = formatDate(new Date(year, month - n + 1, 1));
  return [str, today]
}

export default {
  parseNum,
  parseTime,
  formatRichText,
  timeDifference,
  filterDictText,
  formatYuan,
  formatDate,
  getToday,
  getYesterday,
  getThisWeek,
  getThisMonth,
  getDayAgo,
  getMonthAgo
}
